package com.lagou.common;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class RpcDecoder extends ByteToMessageDecoder {

	private Class<?> clazz;

	private Serializer serializer;

	public RpcDecoder(Class<?> clazz, Serializer serializer) {

		this.clazz = clazz;

		this.serializer = serializer;

	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		int len = in.readableBytes();
		if (len < 1)
			return;
		byte[] bytes = new byte[len];
		in.getBytes(0, bytes);
		out.add(this.serializer.deserialize(clazz, bytes));
		in.skipBytes(len);
	}

}
